package com.link.base.tencent.thirdclient.qq.service;

import com.link.base.base.user.model.User;
import com.link.base.base.user.service.UserService;
import com.link.core.cllog.LCLogger;
import com.link.base.tencent.thirdclient.qq.model.QQLogin;
import com.link.core.basic.service.ServiceException;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * QQ登录服务实现类
 *
 * @author LiQun
 * @date 2018/3/15 11:19
 * update by ouyangzhenqiang at 2018/04/16
 */
@Service
public class QQLoginServiceImpl implements QQLoginService {
    @Resource
    private UserService userService;

    private static final String APP_ENTRANCE = "app";

    @Override
    public QQLogin getQqInfo(QQLogin qqLogin) throws Exception {
        // 从前端授权页面获取到的信息
        String userId = qqLogin.getUserId();
        String uuid = qqLogin.getUuid();
        if (StringUtils.isNotBlank(userId) && StringUtils.isNotBlank(uuid)) {
            // 查询用户信息
            User user = new User();
            user.setQqUnionId(userId);
            user = userService.getBoundAccounts(user);
            LCLogger.info().withMessageKey("getQqInfo").withMessage("根据QQ userId => " + userId + "查询用户是否存在").flush();

            if (user == null) {
                LCLogger.info().withMessageKey("getQqInfo").withMessage(qqLogin.getUserId() + "未绑定用户").flush();

                qqLogin.setBindUser(false);
                qqLogin.setUserId(userId);
            } else {
                LCLogger.info().withMessageKey("getQqInfo").withMessage(qqLogin.getUserId() + "已绑定用户").flush();

                qqLogin.setBindUser(true);
                qqLogin.setLogin(user.getLogin());
                qqLogin.setUserId(userId);
                // 已绑定的情况下，默认其为重新登录登录操作，后台生成loginToken给前端
                String loginToken = userService.mobileGetLoginToken(user.getLogin(), user.getCorpid(), uuid, null, APP_ENTRANCE);
                qqLogin.setLoginToken(loginToken);
            }
        } else {
            throw new ServiceException("THIRDQQ-001");
        }

        return qqLogin;
    }
}
